import os
from pathlib import Path
import pymysql
from corsheaders.defaults import default_headers
pymysql.install_as_MySQLdb()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-_ni5tb1_8ldx5w!=jk7)s(*13ro+76*rsebai+d0g$+$%y=$mo"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
CORS_ALLOWED_ORIGINS = [
    "http://localhost:5173",  # 你的前端地址
    "http://localhost:5174",  # 你的前端地址
]
# CORS_ALLOW_ALL_ORIGINS = True  # 用于调试阶段，生产环境不要开启
# ✅ 开启 cookie 支持
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = [
    "token",
    "content-type",  # 添加这一项
]
# 如果你使用了 Cookie 或者需要认证头：
CORS_ALLOW_CREDENTIALS = True
# Application definition
# ==============配置静态文件=============
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
#======= 结束配置动态文件 ==================
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    'rest_framework.authtoken',
    "rest_framework",
    "article02",
    "blogdemo3",
    'usecasedemo4',
    'casedemo5',
    'casedemo6_login',
    'casedemo7_cache',
    'DjangoUeditor',
    'crispy_forms',
    'blogdemo8',
    'casedemo9_smscode',
    'corsheaders',
    'casedemo10_drf',
    'casedemo11_APIView',
    'casedemo12_view',
    'casedemo13_ser',
    'casedemo14_userSer',
    "casedemo15_authpremiss",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    #"django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "casedemo15_authpremiss.middleware.login_required_middleware.LoginRequiredMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "DJBackendBase.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, 'templates')],# 修改位置
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "DJBackendBase.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
    "default": {
        'ENGINE': 'django.db.backends.mysql',    # 数据库引擎
        'NAME': 'djangobase', # 数据库名称
        'HOST': '127.0.0.1', # 数据库地址，本机 ip 地址 127.0.0.1
        'PORT': 3306, # 端口
        'USER': 'root',  # 数据库用户名
        'PASSWORD': 'root', # 数据库密码
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
#LANGUAGE_CODE = "en-us"
LANGUAGE_CODE = "zh-hans"
#TIME_ZONE = "UTC"
TIME_ZONE = "Asia/Shanghai"
USE_I18N = True
USE_TZ = True
STATIC_URL = "static/"

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

'''
Cache的使用
说明：对于访问量较大的网站，缓存数据就是为了保存那些需要很多计算资源的结果，从而减少不必要的资源消耗
缓存的目的是加快响应速度、减轻数据库或计算压力。在 Django 中，这张表可以存任何你设定为缓存的数据，比如：
常见缓存内容：
    1. 页面片段缓存:某个页面的部分内容不经常变，比如网站导航、热点文章、用户推荐列表等。
    2. 查询结果:比如复杂查询、聚合结果、推荐系统结果，可以缓存 10 分钟或 1 小时。
    4. 验证码、短信验证码:比如用户注册登录时的验证码，设置一个短时间缓存（如5分钟）防止重复发送。
'''
'''
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}'''
CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
        }
    }
}

# 发送邮件设置
# https://docs.djangoproject.com/en/2.0/ref/settings/#email
# https://docs.djangoproject.com/en/2.0/topics/email/
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.qq.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True  # 启用 TLS
EMAIL_HOST_USER = '2269435134@qq.com'
EMAIL_HOST_PASSWORD = 'hqzrizxkyolrdjgc'  # 授权码
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER


# APPEND_SLASH = False
